<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    let input = [
      {
        id: 1,
        val: "学校",
        parentId: null,
      },
      {
        id: 2,
        val: "班级1",
        parentId: 1,
      },
      {
        id: 3,
        val: "班级2",
        parentId: 1,
      },
      {
        id: 4,
        val: "学生1",
        parentId: 2,
      },
      {
        id: 5,
        val: "学生2",
        parentId: 3,
      },
      {
        id: 6,
        val: "学生3",
        parentId: 3,
      },
    ];

    function buildTree(arr, parentId, childrenArray) {
      arr.forEach((item) => {
        if (item.parentId == parentId) {
          item.children = [];
          buildTree(arr, item.id, item.children)
          childrenArray.push(item)
        }
      })
    }
    function arrayToTree(input,parentId) {
      const array = [];
      buildTree(input, parentId, array);
      return array.length > 0 ? (array.length > 1 ? array : array[0]) : {};
    }
    const obj = arrayToTree(input, null)
    console.log(obj)
  </script>
</body>

</html>